//
//  XGChangePasswordViewController.swift
//  TodayNews
//
//  Created by monkey on 2020/4/12.
//  Copyright © 2020 itcast. All rights reserved.
//

import UIKit
import LeanCloud
import MBProgressHUD
import SCLAlertView

class XGChangePasswordViewController: UIViewController,XGUserAccountValidateProtocol
{
    override func loadView()
    {
        super.loadView()
        setUpUI()
    }
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        navigationItem.title = "修改密码"
        NotificationCenter.default.addObserver(self, selector: #selector(textDidChangeNotification), name: UITextField.textDidChangeNotification, object: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
    {
        view.endEditing(true)
    }
    
    // MARK: - 私有属性
    
    /// 原密码
    private lazy var oldPasswordTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder = "请输入原密码"
        textField.clearButtonMode = .whileEditing
        textField.borderStyle = .roundedRect
        textField.font = UIFont.systemFont(ofSize: 17)
        textField.isSecureTextEntry = true
        return textField
    }()
    /// 新密码
    private lazy var passwordTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder = "请输入新密码"
        textField.clearButtonMode = .whileEditing
        textField.borderStyle = .roundedRect
        textField.font = UIFont.systemFont(ofSize: 17)
        textField.isSecureTextEntry = true
        return textField
    }()
    /// 确认密码
    private lazy var confirmPasswordTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder = "确认新密码"
        textField.clearButtonMode = .whileEditing
        textField.borderStyle = .roundedRect
        textField.font = UIFont.systemFont(ofSize: 17)
        textField.isSecureTextEntry = true
        return textField
    }()
    /// 确定按钮
    private lazy var confirmButton: UIButton = { [weak self] in
        let button = UIButton(title: "确定", fontSize: 20, normalColor: UIColor.white, highlightedColor: UIColor.white, target: self, action: #selector(changePasswordAction))
        button.setBackgroundImage(UIColor.colorWithHexString(hexadecimal: "#FF6A6A").toImage(), for: .normal)
        button.setBackgroundImage(UIColor.colorWithHexString(hexadecimal: "#FFAEB9").toImage(), for: .disabled)
        button.isEnabled = false
        button.layer.cornerRadius = 20
        button.layer.masksToBounds = true
        return button
    }()
}

private extension XGChangePasswordViewController
{
    /// textField通知监听方法
    @objc func textDidChangeNotification() -> Void
    {
        confirmButton.isEnabled = oldPasswordTextField.hasText && passwordTextField.hasText && confirmPasswordTextField.hasText
    }
    
    /// 修改密码事件
    @objc func changePasswordAction() -> Void
    {
        view.endEditing(true)
        
        guard let user = LCApplication.default.currentUser else {
            return
        }
        
        if passwordTextField.text != confirmPasswordTextField.text {
            MBProgressHUD.showErrorTips(text: "两次密码输入不一致!")
        } else if !validatePassword(password: passwordTextField.text!) {
            MBProgressHUD.showErrorTips(text: "密码长度应设置在6~18位!")
        } else {
            // 更新密码
            user.updatePassword(oldPassword: oldPasswordTextField.text!, newPassword: passwordTextField.text!) { (result) in
                if result.isSuccess {
                    // 密码修改成功
                    MBProgressHUD.showSuccessTips(text: "修改密码成功!")
                    // 弹框重新登录
                    DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                        let alert = SCLAlertView(appearance: SCLAlertView.SCLAppearance(showCloseButton: false))
                        alert.addButton("确定") {
                            // 发送通知 回到登录页面
                            NotificationCenter.default.post(name: kSwitchKeyWindowRootViewControllerNotification, object: XGLoginViewController.self, userInfo: nil)
                        }
                        alert.showInfo("提示", subTitle: "您的身份认证已过期,请重新登录!")
                    }
                } else {
                    MBProgressHUD.showErrorTips(text: result.error?.reason ?? "修改密码失败!")
                }
            }
        }
    }
    
    func setUpUI() -> Void
    {
        view.backgroundColor = UIColor.white
        
        view.addSubview(oldPasswordTextField)
        view.addSubview(passwordTextField)
        view.addSubview(confirmPasswordTextField)
        view.addSubview(confirmButton)
        
        oldPasswordTextField.snp.makeConstraints { (make) in
            make.top.equalTo(view.snp.topMargin).offset(30)
            make.left.equalToSuperview().offset(30)
            make.right.equalToSuperview().offset(-30)
            make.height.equalTo(44)
        }
        passwordTextField.snp.makeConstraints { (make) in
            make.top.equalTo(oldPasswordTextField.snp.bottom).offset(30)
            make.left.equalToSuperview().offset(30)
            make.right.equalToSuperview().offset(-30)
            make.height.equalTo(44)
        }
        confirmPasswordTextField.snp.makeConstraints { (make) in
            make.top.equalTo(passwordTextField.snp.bottom).offset(30)
            make.left.right.height.equalTo(passwordTextField)
            make.height.equalTo(44)
        }
        confirmButton.snp.makeConstraints { (make) in
            make.top.equalTo(confirmPasswordTextField.snp.bottom).offset(30)
            make.centerX.equalToSuperview()
            make.size.equalTo(CGSize(width: ceil(TodayNews_Screen_Width * 0.6), height: 44))
        }
    }
}
